package com.moodincode.taskcenter.script;

import org.springframework.http.HttpCookie;
import org.springframework.http.HttpHeaders;
import org.springframework.http.ResponseCookie;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.util.CollectionUtils;
import org.springframework.util.MultiValueMap;
import org.springframework.util.StringUtils;

import java.util.List;
import java.util.Map;


/**
 * @author moodincode
 */
public class RequestDataUtil {
    /**
     * 问号,与符号,等号
     */
    public static final String  DOUBTS_FLAG="\\?",AND_FLAG="&",EQ_FLAG="=";
    /**
     * 解析cookie
     * @param response
     * @return
     */
    public static Cookie parseCookiesResponseParam(ServerHttpResponse response) {
        Cookie cookie=new Cookie();
        if(response.getCookies()!=null){
            for (List<ResponseCookie> httpCookieList : response.getCookies().values()) {
                for (ResponseCookie responseCookie : httpCookieList) {
                    cookie.put(responseCookie.getName(),responseCookie.getValue());
                }
            }
        }
        return cookie;
    }
    /**
     * 解析cookie
     * @param request
     * @return
     */
    public static Cookie parseCookiesParam(ServerHttpRequest request) {
        Cookie cookie=new Cookie();
        if(request.getCookies()!=null){
            for (List<HttpCookie> cookies : request.getCookies().values()) {
                for (HttpCookie httpCookie : cookies) {
                    cookie.put(httpCookie.getName(),httpCookie.getValue());
                }
            }
        }
        return cookie;
    }
    /**
     * 解析请求头
     * @param headers
     * @return
     */
    public static Header parseHeaderParam(HttpHeaders headers) {
        Header headerMap=new Header();
        for (Map.Entry<String, List<String>> stringListEntry : headers.entrySet()) {
            if(!CollectionUtils.isEmpty(stringListEntry.getValue())){
                headerMap.put(stringListEntry.getKey(),stringListEntry.getValue().get(0));
            }
        }
        return headerMap;
    }
    /**
     * 解析请求URL参数
     * @param request
     * @return
     */
    public static Query parseQueryParam(ServerHttpRequest request) {
        Query query=new Query();
        MultiValueMap<String, String> queryParams = request.getQueryParams();
        if(!CollectionUtils.isEmpty(queryParams)){
            for (String key : queryParams.keySet()) {
                String value = queryParams.getFirst(key);
                query.put(key,value);
            }
        }else if(StringUtils.hasText(request.getURI().getQuery())){
            for (String param : request.getURI().getQuery().split(AND_FLAG)) {
                String[] pair = param.split(EQ_FLAG);
                int length = pair.length;
                if(length ==1){
                    query.put(pair[0],"");
                }else if(length ==2){
                    if(pair[0].length()+pair[1].length()+1<param.length()){
                        query.put(pair[0],param.substring(pair[0].length()+1));
                    }else {
                        query.put(pair[0],pair[1]);
                    }

                }else if(length >2){
                    int keyLen = pair[0].length();
                    if(keyLen+1<param.length()){
                        query.put(pair[0],param.substring(keyLen+1));
                    }
                }
            }
        }
        return query;
    }
    /**
     * 解析请求www-from-urlencode参数
     * @return
     */
    public static Param parseFormDataParam(String dataString) {
        Param fromParam=new Param();
        for (String param : dataString.split(AND_FLAG)) {
            String[] pair = param.split(EQ_FLAG);
            int length = pair.length;
            if(length ==1){
                fromParam.put(pair[0],"");
            }else if(length ==2){
                if(pair[0].length()+pair[1].length()+1<param.length()){
                    fromParam.put(pair[0],param.substring(pair[0].length()+1));
                }else {
                    fromParam.put(pair[0],pair[1]);
                }

            }else if(length >2){
                int keyLen = pair[0].length();
                if(keyLen+1<param.length()){
                    fromParam.put(pair[0],param.substring(keyLen+1));
                }
            }
        }

        return fromParam;
    }

    /**
     * 解析URL中的参数
     * @param path 请求路径的参数例如 test/123
     * @param url 匹配参数的路径,例如 test/{id}
     * @return
     */
    public static PathVariable parsePathVariable(String path, String url) {
        PathVariable pathVariable=new PathVariable();
        String[] pathArrs = path.split("/");
        String[] urlArrs = url.split("/");
        //比较判断
        if(pathArrs.length== urlArrs.length) {
            for (int i = 0; i < pathArrs.length; i++) {
                String pathArr = pathArrs[i];
                if (pathArr.startsWith("{") && pathArr.endsWith("}")) {
                    //解析参数
                    pathVariable.put(pathArr.substring(1,pathArr.length()-1),urlArrs[i]);
                }
            }
        }
        return pathVariable;
    }

    /**
     * @param path 请求路径的参数例如 test/123
     * @param url 匹配参数的路径,例如 test/{id}
     * @return
     */
    public static boolean isMatchPathVariable(String path, String url){
        String[] pathArrs = path.split("/");
        String[] urlArrs = url.split("/");
        //比较判断
        if(pathArrs.length== urlArrs.length){
            for (int i = 0; i < pathArrs.length; i++) {
                String pathArr = pathArrs[i];
                if(pathArr.startsWith("{")&&pathArr.endsWith("}")){
                    continue;
                }else if(!pathArr.equals(urlArrs[i])){
                   return false;
                }
            }
            return true;
        }
        return false;
    }
}
